// pages/forgetPassWord1/forgetPassWord1.js
import ForgetPassWordApi from '../../api/forgetPassWord.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    code:'',
    time: 60 * 1000,
    codeFlag:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  async nextStep(){
    const phone = this.data.phone
    const code = this.data.code
    if(phone == ''){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(code == ''){
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    //判断验证码是否正确
    const param = {
      telNum :phone,
      verifyCode:code
    }
    const res = await ForgetPassWordApi.checkVerifyCode(param)
    if(res.code == 100){
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }else{
      //如果正确，进入下一个页面
      wx.navigateTo({
        url: `/pages/forgetPassWord2/forgetPassWord2?phone=${phone}`
      })
    } 
  },
  /**
   * 返回
   */
  handlerGobackClick(){
    wx.navigateBack()
  },
  /**
   * 发送验证码
   */
  async sendCode(){
    if (this.data.codeFlag){
      return
    }
    const phone = this.data.phone
    const code = this.data.code
    if(phone == ''){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    //验证手机号是否正确
    if(!(/^1[34578]\d{9}$/.test(phone))){
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    const res = await ForgetPassWordApi.forgetSendCode({telNum:phone})
    if(res.code == 100){
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }else {
      //如果存在，开始倒计时
      this.setData({
        codeFlag:true
      })
      this.start()
    }
  },
  /**
   * input 数据绑定
   */
  updateValue(e) {
    let name = e.currentTarget.dataset.name;
    let nameMap = {}
    nameMap[name] = e.detail
    this.setData(nameMap)
  },
  /**
   * 倒计时开始
   */
  start() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
  },
  /**
   * 倒计时结束
   */
  finished() {
    this.setData({
      codeFlag:false
    })
  },
})
